import { showToast, showLoading } from '/utils/utils.js';

// let host = '/api/';
let host = 'https://newapi.wanzhuanbendi.com/official/'

export const request = (params) => {
	let url = params.url;
	if (!url.includes('http')) url = host + url;

	let header = params.header || {};
	header['content-type'] = 'application/x-www-form-urlencoded';

	let token = uni.getStorageSync('userInfo').access_token;
	if (token) header['Token'] = token;

	let data = params.data || {};

	let runOver = false;
	if (!params.hideLoading) {
		setTimeout(() => {
			if (!runOver) showLoading('加载中');
		}, + params.delayLoading * 450);
	}

	return new Promise((success, error) => {
		uni.request({
			url,
			header,
			method: 'POST',
			data,
			dataType: 'json',
			sslVerify: false
		}).then(res => {
			if (res.data.code === 200 || !res.data.errcode) {
				success(res.data);
			} else {
				showToast(res.data.errmsg || '网络错误', 'none', false, 200);
				error(res.data);
			}
		}).catch(err => {
			error(err.data);
		}).finally(() => {
			runOver = true;
			if (params.autoHideLoading !== false) uni.hideLoading();
		});
	});
}